import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, PageHeader, Divider, Badge, Row } from 'antd';
import '@/assets/css/settings';
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, compareNum, TableCustomize, openSuccessModal, openModalMessage, compareString, compareDate } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import SearchForm from './SearchFormDetails';
import * as MaterialReceivingService from '../../../axios/CommissioningManagement'
import ReceiveComponent from './ReceiveComponent';
import { getDateHHMMYY_HHMMSS } from '../../../utils/action'
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')
const { confirm } = Modal

class MaterialReceiving_details extends Component {
	state = {
		dataSource: [],
		visible: false,
		advanced: false,
		searchItem: {},
		pageSize: 10,
		pageNum: 1,
		total: 40,
		statusList: [
			{ id: 0, value: '新建' },
			{ id: 1, value: '合格' },
			{ id: 2, value: '异常' },
			{ id: 9, value: '删除' },
		],
		columns: [
			{
				title: '序号',
				dataIndex: 'dataIndex',
				width: 100,
				render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
			},
			{
				title: '领料单号',
				dataIndex: 'batchNo1',
				width: 100,
				sorter: (a, b) => compareString(a.batchNo1, b.batchNo1)
			},
			{
				title: '批号',
				dataIndex: 'batchNo',
				width: 100,
				sorter: (a, b) => compareString(a.batchNo, b.batchNo)
			},

			{
				title: '机型',
				width: 100,
				dataIndex: 'model',
				sorter: (a, b) => compareString(a.model, b.model),
				// editable: true
			},
			{
				title: '领料车间',
				width: 100,
				// allowEllipsis: true,
				dataIndex: 'department1',
				sorter: (a, b) => compareString(a.department1, b.department1)
			},
			{
				title: '领料班组',
				width: 100,
				// allowEllipsis: true,
				dataIndex: 'department',
				sorter: (a, b) => compareString(a.department, b.department)
			},
			{
				title: '班组长',
				width: 100,
				// allowEllipsis: true,
				dataIndex: 'assembleProcess',
				sorter: (a, b) => compareString(a.assembleProcess, b.assembleProcess)
			},
			{
				title: '领料项',
				width: 100,
				// allowEllipsis: true,
				dataIndex: 'testMachineProcess',
				sorter: (a, b) => compareString(a.testMachineProcess, b.testMachineProcess)
			},
			{
				title: '申请时间',
				width: 100,
				// allowEllipsis: true,
				dataIndex: 'qualityCheckProcess',
				sorter: (a, b) => compareDate(a.qualityCheckProcess, b.qualityCheckProcess)
			},
			{
				title: '装配开始时间',
				width: 150,
				dataIndex: 'isStates',
				sorter: (a, b) => compareDate(a.isStates, b.isStates),
			},
			{
				title: '需求时间',
				width: 150,
				dataIndex: 'firstDeliveryTime',
				sorter: (a, b) => compareDate(a.firstDeliveryTime, b.firstDeliveryTime)
			},
			{
				title: '操作',
				width: 100,
				dataIndex: 'opts',
				render: (text, record) => <>
					<a onClick={() => this.create(1, record)}>接收</a>
				</>
			}
		],
		selectedRows: [],
		selectedRowKeys: [],
		locationData: {},
		searchItemFather: {},
		loading: false,
		downloadLoading: false,
		editRow: {},
		modalTitle: '',

		chooseRecord: [],
	};
	componentDidMount() {
		console.log(this.props.location.data)
		this.setState({ locationData: this.props.location.data ? this.props.location.data.record : JSON.parse(localStorage.getItem('MaterialReceiving_detailsList')), searchItemFather: this.props.location.data ? this.props.location.data.searchItem : JSON.parse(localStorage.getItem('MaterialReceiving_searchItem')) }, this.fetch)
		// this.fetch();
	}
	componentWillUnmount() {
		this.setState = () => {
			return;
		};
	}
	//初始化加载数据
	fetch = (pageNum = 1, pageSize = 100) => {
		this.setState({ loading: true });
		const { locationData, searchItem } = this.state;
		const data = { ...locationData, ...searchItem }
		data.pageNum = pageNum;
		data.pageSize = pageSize;
		console.log(data);
		MaterialReceivingService.findMachineReport(data).then(res => {
			this.setState({ loading: false })
			if (res.data.code !== 200) {
				openModalMessage('warning', res.data.data.msg);
				return;
			}
			this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize });
		}).catch(err => {
			openModalMessage('error', err.message);
		})
	}


	handleSearch = value => {
		this.setState({ searchItem: value }, this.fetch);
	};

	onHandleAdvanced = () => {
		this.setState({ advanced: !this.state.advanced })
	}
	// table行修改数据
	loadData = (value, dataSource) => {
		console.log(value, dataSource)
	}

	//0批量 1单独  接收
	create = (type, record = {}) => {
		const { selectedRows } = this.state
		let chooseRecord = []
		if (type === 1) {
			chooseRecord.push(record)
		} else {
			if (!selectedRows || !selectedRows.length) {
				openModalMessage('warning', '请选择要接收的单据！');
				return;
			}
			chooseRecord = selectedRows
		}
		this.setState({
			visible: true,
			modalTitle: '物料接收确认',
			chooseRecord,
		});
	};

	resetForm = () => {
		this.formSearch && this.formSearch.resetFields();
		this.setState({ searchItem: {} }, this.fetch);
	}


	//接收
	submitReceive = () => {
		this.setState({ btnLoading: true });

		let obj = {
			"userId": localStorage.getItem('userId')
		}

		console.log(obj);
		// ProductionOrderService.addWorkOrderDispatch(obj).then(res => {
		//   this.setState({ btnLoading: false });
		//   if (res.data.code !== 200) {
		//     openModalMessage('warning', res.data.msg);
		//     return;
		//   }
		//   const that = this;
		//   Modal.confirm({
		//     title: res.data.msg,
		//     okText: '继续操作',
		//     cancelText: '关闭',
		//     icon: <Icon type="check-circle" theme="twoTone" twoToneColor="#52c41a" />,
		//     centered: true,
		//     onOk() { },
		//     onCancel() {
		//       that.handleCancel();
		//       that.setState({ GroupList: [], ProcessList: [], BatchNoList: [] })
		//     },
		//   });
		// }).catch(err => {
		//   this.setState({ btnLoading: false });
		//   openModalMessage('error', err.message)
		// })
	}

	handleCancel = e => {
		this.setState({
			selectedRowKeys: [],
			selectedRows: [],
			visible: false,
			btnLoading: false,
		});
		// this.fetch();
	};
	render() {
		const { btnLoading, selectedRowKeys, selectedRows, locationData, loading, dataSource, advanced, columns, pageNum, pageSize, total, searchItemFather, searchItem, downloadLoading, statusList, modalTitle, visible, chooseRecord } = this.state;
		const spanStyle = { color: '#fd1818', margin: '0 3px' }
		const rowSelection = {
			type: 'checkbox',
			selectedRowKeys: selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedRows: selectedRows,
					selectedRowKeys: selectedRowKeys,
				})
			},
			onSelectAll: (selected, selectedRows, changeRows) => {
				const keys = [... this.state.selectedRowKeys];
				const rows = [... this.state.selectedRows];
				if (selected) {
					changeRows.forEach(row => {
						if (isInvalidObject(keys.find(key => key === row.machineDetailsId))) {
							keys.push(row.machineDetailsId);
							rows.push(row);
						}
					})
				} else {
					changeRows.forEach(row => {
						keys.splice(keys.indexOf(row.machineDetailsId), 1);
						rows.splice(rows.indexOf(row), 1);
					})
				}
				this.setState({ selectedRows: rows, selectedRowKeys: keys })
			}
		}
		return (
			<div>
				<BasicLayoutSearch>
					<PageHeader
						style={{ padding: '4px 24px' }}
						onBack={() => this.props.history.push({ pathname: '/MaterialReceiving', data: searchItemFather })}
						title={`领料单接收详细数据`}>
					</PageHeader>
					<Divider />
					<SearchForm onSearch={this.handleSearch}
						onClick={this.onHandleAdvanced}
						advanced={advanced} searchItem={searchItem}
						statusList={statusList}
						resetForm={this.resetForm}
						ref={node => (this.formSearch = node)} />
				</BasicLayoutSearch>
				<BasicLayout buttons={[
					<Button key={2} onClick={this.create} type='primary' icon='vertical-align-bottom'>批量接收</Button>,
					<Button key={2} onClick={() => this.fetch()} type='primary' icon='redo'>刷新</Button>,
				]} name={`领料单接收详细数据`} icon="table">
					<TableCustomize
						columns={columns}
						rowKey={(record) => record.batchNo}
						rowSelection={rowSelection}
						dataSource={dataSource}
						pagination={false}
						loading={loading}
						allowDrafting={true}
						allowEditable={this.loadData} />
					<BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
				</BasicLayout>

				{/* 接收 */}
				<Modal
					visible={visible}
					destroyOnClose
					title={modalTitle}
					onOk={this.submitReceive}
					onCancel={this.handleCancel}
					okText="确认"
					cancelText="取消"
					width={'70%'}
					maskClosable={false}
					confirmLoading={btnLoading}
				>
					<ReceiveComponent chooseRecord={chooseRecord} />
				</Modal>
			</div>
		);
	}
}
export default Form.create()(withRouter(MaterialReceiving_details));